package com.lb.shopguide.ui.activity;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.ImCache;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseActivity;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.GuideAdBean;
import com.lb.shopguide.entity.UpdateInfoBean;
import com.lb.shopguide.entity.UserBean;
import com.lb.shopguide.entity.trace.TraceBean;
import com.lb.shopguide.event.guide.ActivityFinishEvent;
import com.lb.shopguide.event.guide.BindStaffEvent;
import com.lb.shopguide.event.guide.ChangeStaffEvent;
import com.lb.shopguide.event.guide.FansTransToMemberEvent;
import com.lb.shopguide.event.guide.GuideDivideUpdateEvent;
import com.lb.shopguide.event.guide.HomeMijiEvent;
import com.lb.shopguide.event.guide.HomeOrderRefreshEvent;
import com.lb.shopguide.event.guide.HomeRecommendEvent;
import com.lb.shopguide.event.guide.NewFansEvent;
import com.lb.shopguide.event.jump.JumpMemberEvent;
import com.lb.shopguide.event.jump.JumpRecEvent;
import com.lb.shopguide.im.Preference.UserPreferences;
import com.lb.shopguide.manager.service.update.UpdateManager;
import com.lb.shopguide.manager.service.LoginStatusService;
import com.lb.shopguide.trace.TraceManager;
import com.lb.shopguide.ui.fragment.guide.FragmentMain;
import com.lb.shopguide.util.lb.BizUtil;
import com.netease.nim.uikit.support.permission.BaseMPermission;
import com.netease.nim.uikit.support.permission.MPermission;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionDenied;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionGranted;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionNeverAskAgain;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.StatusCode;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

public class GuideMainActivity extends BaseActivity {

    private boolean isExit = false;

    private UserBean userBean;
    private UpdateInfoBean updateInfoBean;
    private GuideAdBean guideAdBean;

    private UserConfigManager mUserConfigManager;

    private LbReceiver mLbReceiver;

    private final int BASIC_PERMISSION_REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化消息提醒配置
        initNotificationConfig();
        initData();
        registerReceiver();
        requestBasicPermission();
        if (savedInstanceState == null) {
            loadRootFragment(R.id.fl_container, FragmentMain.newInstance(guideAdBean));
        }
        loginPush();
        checkImStatus();
        startImService();
        dealJump(getIntent());
    }


    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return super.onCreateFragmentAnimator();
    }


    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            exitBy2Click();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        dealJump(intent);
        checkImStatus();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        showTestNotification(this);
        if (AppConfigManager.getAppconfigManager(this).getVersionCode() != AppUtils.getAppVersionCode()) {
            TraceBean bean = new TraceBean();
            bean.setXdCode("XD0007");
            bean.setYdCode("YD0008");
            bean.setRelBusinessCode("" + AppUtils.getAppVersionCode());
            AppConfigManager.getAppconfigManager(this).setVersionCode(AppUtils.getAppVersionCode());
            TraceManager.getTraceManager(this).trackUpdateApp(bean);
        }

    }

    private void showTestNotification(Context context) {
//                    String appName = context.getResources().getString(R.string.app_name);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
        Bundle targetBundle = new Bundle();
        targetBundle.putInt(AppConstant.NOTIFICATION_TARGET, AppConstant.NOTIFICATION_TARGET_MEMBER);
        Intent targetIntent = new Intent(context, GuideMainActivity.class);
        targetIntent.putExtras(targetBundle);
        mBuilder.setContentTitle("测试")//设置通知栏标题
                .setContentText("真的是测试") //设置通知栏显示内容
                .setContentIntent(PendingIntent.getActivity(context, 1, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT)) //设置通知栏点击意图
//  .setNumber(number) //设置通知集合的数量
                .setTicker(JPushInterface.EXTRA_NOTIFICATION_TITLE + "消息")//通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
//.setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                .setSound(Uri.parse("android.resource://" + GuideApplication.getAppContext().getPackageName() + "/" + R.raw.beep))
                .setSmallIcon(R.drawable.logo);//注：PendingIntent开启新的界面，intent携带值传递的时候，PendingIntent的类型是FLAG_UPDATE_CURRENT，新的值过来，自动更新，intent需要设置Action才可以获得传递的值
        mNotificationManager.notify(100, mBuilder.build());
    }

    private void dealJump(Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle != null && bundle.containsKey(AppConstant.NOTIFICATION_TARGET)) {
            int target = bundle.getInt(AppConstant.NOTIFICATION_TARGET);
            switch (target) {
                case AppConstant.NOTIFICATION_TARGET_MEMBER:
                    EventBus.getDefault().postSticky(new JumpMemberEvent());
                    break;
                case AppConstant.NOTIFICATION_TARGET_REC:
                    EventBus.getDefault().postSticky(new JumpRecEvent(bundle.getString(AppConstant.NOTIFICATION_INFO)));
                    break;
            }
        }
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConstant.BROADCAST_ROB);
        intentFilter.addAction(AppConstant.BROADCAST_UPDATE);
//        intentFilter.addAction(AppConstant.BROADCAST_LOGIN);
        intentFilter.addAction(AppConstant.BROADCAST_CHANGE_STAFF);
        intentFilter.addAction(AppConstant.BROADCAST_ESOTERICA);
        intentFilter.addAction(AppConstant.BROADCAST_RECOMMEND);
        intentFilter.addAction(AppConstant.BROADCAST_BIND_STAFF);
        intentFilter.addAction(AppConstant.BROADCAST_STAFF_DIVIDE);
//        intentFilter.addAction(AppConstant.BROADCAST_WAP_QRPAY);
        intentFilter.addAction(AppConstant.BROADCAST_FANS_NEW);
        intentFilter.addAction(AppConstant.BROADCAST_FANS_CHANGE);
        registerReceiver(mLbReceiver, intentFilter);
    }

    private void unRegisterReceiver() {
        if (mLbReceiver != null) {
            this.unregisterReceiver(mLbReceiver);
        }
    }

    private void initData() {
        mLbReceiver = new LbReceiver();
        mUserConfigManager = UserConfigManager.getInstance(this);
        Intent intent = getIntent();
        if (intent.hasExtra(AppConstant.UPDATE_BEAN)) {
            //更新逻辑
            updateInfoBean = (UpdateInfoBean) intent.getSerializableExtra(AppConstant.UPDATE_BEAN);
            if (updateInfoBean != null && updateInfoBean.isForce()) {//如果强制更新，才显示更新
                //不显示更新，且版本相等
                if (!mUserConfigManager.isShowUpdate() && mUserConfigManager.getUpdateVersion().equals(updateInfoBean.getAppVersion())) {

                } else {
                    if (BizUtil.compareVersion(updateInfoBean.getAppVersion(), AppUtils.getAppVersionName())) {
                        UpdateManager updateManager = new UpdateManager(this);
                        updateManager.showUpdateInfo(updateInfoBean, getSupportFragmentManager());
                    }
                }
            }
        }
        if (intent.hasExtra(AppConstant.GUIDEAD_BEAN)) {
            guideAdBean = (GuideAdBean) intent.getSerializableExtra(AppConstant.GUIDEAD_BEAN);
        }
    }

    private void initNotificationConfig() {
        // 初始化消息提醒
        NIMClient.toggleNotification(true);

        // 加载状态栏配置
        StatusBarNotificationConfig statusBarNotificationConfig = UserPreferences.getStatusConfig();
        if (statusBarNotificationConfig == null) {
            statusBarNotificationConfig = ImCache.getNotificationConfig();
            UserPreferences.setStatusConfig(statusBarNotificationConfig);
        }
        // 更新配置
        NIMClient.updateStatusBarNotificationConfig(statusBarNotificationConfig);
    }

    private void checkImStatus() {
        StatusCode status = NIMClient.getStatus();
        if (status == StatusCode.KICKOUT || status == StatusCode.UNLOGIN) {
            ToastUtils.showShort("您的账号已在别处登录");
            otherClientLogin();
        }
    }

    private void startImService() {
        startService(getImServiceIntent());
    }

    private Intent getImServiceIntent() {
        return new Intent(GuideApplication.getAppContext(), LoginStatusService.class);
    }

    public void onSessionOutOfDate() {
        if (mUserConfigManager == null) {
            mUserConfigManager = UserConfigManager.getInstance(this);
        }
        BizUtil.logout(this, mUserConfigManager);
    }

    public void setUserBean(UserBean userBean) {
        this.userBean = userBean;
    }

    public UserBean getUserBean() {
        return userBean;
    }

    public UpdateInfoBean getUpdateInfoBean() {
        return updateInfoBean;
    }


    private void loginPush() {
        Set<String> tags = new HashSet<>();
        tags.add(mUserConfigManager.getStoreCode());
        tags.add("All_STORE");
        JPushInterface.setAlias(this, AppConstant.SEQUENCE_SET_ALIAS, mUserConfigManager.getUserId());
        JPushInterface.setTags(this, AppConstant.SEQUENCE_SET_TAGS, tags);
    }

    //以后放到别的地方,双击退出android应用
    private void exitBy2Click() {
        Timer tExit = null;
        if (!isExit) {
            isExit = true; // 准备退出
            ToastUtils.showShort("再按一次退出程序");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            System.exit(0);
        }
    }

    public class LbReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(AppConstant.BROADCAST_ROB)) {
                EventBus.getDefault().post(new HomeOrderRefreshEvent());
            } else if (intent.getAction().equals(AppConstant.BROADCAST_UPDATE)) {
                EventBus.getDefault().post(new HomeOrderRefreshEvent());
            } else if (intent.getAction().equals(AppConstant.BROADCAST_ESOTERICA)) {
                Bundle bundle = intent.getExtras();
                EventBus.getDefault().post(new HomeMijiEvent(bundle.getString(JPushInterface.EXTRA_EXTRA)));
            } else if (intent.getAction().equals(AppConstant.BROADCAST_RECOMMEND)) {
                EventBus.getDefault().post(new HomeRecommendEvent());
            } else if (intent.getAction().equals(AppConstant.BROADCAST_CHANGE_STAFF)) {
                Bundle bundle = intent.getExtras();
                try {
                    JSONObject jsonObject = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    EventBus.getDefault().post(new ChangeStaffEvent(jsonObject.getString("accid")));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (intent.getAction().equals(AppConstant.BROADCAST_BIND_STAFF)) {
                EventBus.getDefault().post(new BindStaffEvent());
            } else if (intent.getAction().equals(AppConstant.BROADCAST_STAFF_DIVIDE)) {
                EventBus.getDefault().post(new GuideDivideUpdateEvent());
            } else if (intent.getAction().equals(AppConstant.BROADCAST_FANS_NEW)) {
                EventBus.getDefault().post(new NewFansEvent());
            } else if (intent.getAction().equals(AppConstant.BROADCAST_FANS_CHANGE)) {
                EventBus.getDefault().post(new FansTransToMemberEvent());
            } else if (intent.getAction().equals(AppConstant.BROADCAST_ACTIVITY_FINISH)) {
                EventBus.getDefault().post(new ActivityFinishEvent());
            }
        }
    }

    private void otherClientLogin() {
        onSessionOutOfDate();
    }


    /**
     * 基本权限管理 todo 用https://github.com/googlesamples/easypermissions替换
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
    };

    private void requestBasicPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(GuideMainActivity.this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
//        Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
//        Toast.makeText(this, "未全部授权，部分功能可能无法正常运行！", Toast.LENGTH_SHORT).show();
        List<BaseMPermission.MPermissionResultEnum> result = MPermission.getPermissionResult(this, BASIC_PERMISSIONS);
        for (int i = 0; i < BASIC_PERMISSIONS.length; i++) {
            if (BASIC_PERMISSIONS[i].equals(Manifest.permission.RECORD_AUDIO)) {
                Toast.makeText(this, "请打开录音权限，否则将无法录音", Toast.LENGTH_LONG).show();
            }
            if (BASIC_PERMISSIONS[i].equals(Manifest.permission.CAMERA)) {
                Toast.makeText(this, "请打开拍照权限，否则将无法拍照", Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterReceiver();
        stopService(getImServiceIntent());
    }
}
